package com.dl.code.config;

import com.dl.code.realm.UserRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

/**
 * Created with IntelliJ IDEA.
 * 作者: DL代先生
 * 日期: 2021/5/28
 * 时间: 20:09
 * 内容: Shiro与springboot整合教程！
 * 描述: shiro的配置
 */
@Configuration
public class ShiroConfig {

    /**
     * 创建自定义的Realm
     * @return
     */
    @Bean
    public UserRealm getUserRealm(){
        //创建自定义的Realm
        UserRealm userRealm = new UserRealm();
        //创建凭证匹配器
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        //设置凭证匹配器采用md5算法进行加密
        credentialsMatcher.setHashAlgorithmName("md5");
        //设置Hash散列次数
        credentialsMatcher.setHashIterations(1024);
        //给Realm设置凭证匹配器
        userRealm.setCredentialsMatcher(credentialsMatcher);
        return userRealm;
    }

    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(UserRealm realm){
        //创建默认的web安全管理器对象
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //给安全管理器对象设置realm
        securityManager.setRealm(realm);
        //返回安全管理器对象
        return securityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultSecurityManager securityManager){
        //创建Shiro的过滤器
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroFilter.setSecurityManager(securityManager);
        //设置未认证的时候的访问页面
        shiroFilter.setLoginUrl("/page/unLogin");
        //设置未授权的时候的访问页面
        shiroFilter.setUnauthorizedUrl("/page/unauthorized");
        //创建一个map集合
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
        //登录页面可以匿名访问
        linkedHashMap.put("/page/login","anon");
        //主页面授权之后可以访问
        linkedHashMap.put("/page/index","authc");
        //设置具有对应权限才可以访问的资源perms[user:delete]
        linkedHashMap.put("/page/studentDelete","perms[sys:student:delete]");
        linkedHashMap.put("/page/studentUpdate","perms[sys:student:update]");
        linkedHashMap.put("/page/studentAdd","perms[sys:student:add]");
        shiroFilter.setFilterChainDefinitionMap(linkedHashMap);
        return shiroFilter;
    }
}
